package com.cn.util;


import com.cn.entity.User;

import java.sql.*;

public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/java";
    private static final String Driver = "com.mysql.jdbc.Driver";
    private static final String NAME = "root";
    private static final String PASSWORD = "12345";
    public static Connection conn = null;
    public static PreparedStatement pstm = null;
    public static Statement stmt = null;
    public static ResultSet rs = null;
    public static User user = null;
    public static int count = 0;
//通用查询
    public static ResultSet query(String sql, Object[] params) {
        try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(URL, NAME, PASSWORD);
            pstm = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstm.setObject(i + 1, params[i]);
                }
            }
            rs = pstm.executeQuery();
            return rs;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
//关闭
    public static void closeAll(ResultSet rs, PreparedStatement pstm, Connection conn) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstm != null) {
                pstm.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

//注册
    public static  Boolean update(String sql, Object[] params){
        try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(URL, NAME, PASSWORD);
            pstm = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    pstm.setObject(i + 1, params[i]);
                }
            }
            count= pstm.executeUpdate();
            if(count>0){
                return true;
            }
            else{
                return false;
            }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                return false;
            } catch (SQLException e) {
                e.printStackTrace();
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }finally {
            DBUtil.closeAll(rs,pstm,conn);
        }
    }

}
